<template>
  <div class="meeting-page flex gap-8 justify-center  min-h-screen pb-16 mx-6">
    <!-- 左侧分组/筛选区 -->
    <!-- <div class="meeting-sidebar">
      <div class="sidebar-card">
        <el-menu :default-active="activeGroup" class="rounded-2xl shadow-lg" @select="onGroupChange">
          <el-menu-item index="mine">我创建的会议</el-menu-item>
          <el-menu-item index="joined">我参与的会议</el-menu-item>
          <el-menu-item index="notStarted">未开始的会议</el-menu-item>
          <el-menu-item index="ongoing">进行中的会议</el-menu-item>
          <el-menu-item index="ended">已结束的会议</el-menu-item>
        </el-menu>
        <div class="sidebar-divider"></div> 
        <el-button
          v-if="userInfo.meeting==1"
          type="primary"
          size="large"
          class="create-meeting-btn"
          @click="openDialog()"
          block
        >
          <el-icon class="mr-1"><Plus /></el-icon>
          新建会议
        </el-button>
      </div>
    </div> -->
    <!-- 右侧内容区 -->
    <div class="flex-1 max-w-[1200px] min-w-0 ">

      <div class="bg-white rounded-2xl shadow-lg p-4">
        <div class="flex">
        <LfTabs :activeIndex="activeIndex" ref="lfTabsRef" :tabOptions="meetingClassList"
          :onTopicClick="changeSubmitType" style="margin-bottom: 20px;" />
                  <el-button
          v-if="userInfo.meeting==1"
          type="primary"
          size="large"
          class="create-meeting-btn"
          @click="openDialog()"
          block
        >
          <el-icon class="mr-1"><Plus /></el-icon>
          新建会议
        </el-button>
        </div>
        <MeetingListPro
          :meetings="meetings"
          :type="activeGroup"
          :loading="loading"
          @edit="openDialog"
          @delete="onDelete"
          @cancel="onCancel"
          @invite="onInvite"
          @manageParticipants="onManageParticipants"
          @detail="onViewDetail"
          @exit="onExit"
          @join="onJoinMeeting"
        />
        
        <!-- 分页组件 -->
        <div v-if="total > 0" class="flex justify-center mt-6">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
      <MeetingDialog v-model:visible="dialogVisible" :meeting="editingMeeting" @save="onSave" />
      <MeetingInvite v-model:visible="inviteVisible" :meeting="inviteMeeting" />
      <MeetingParticipants v-model:visible="participantsVisible" :meeting="participantsMeeting" :type="activeGroup" />
      <MeetingDetailDialog v-model:visible="detailVisible" :meeting="detailMeeting" />
      <!-- 会议 Webview 页面改为通过路由跳转，不在此处使用弹窗组件 -->
    </div>
  </div>
  <el-dialog v-model="joinDialogVisible" title="加入会议" width="400px" :close-on-click-modal="false">
    <div class="text-lg mb-4">是否加入会议 {{ joinMeetingName }}？</div>
    <template #footer>
      <el-button @click="handleJoinMeetingCancel">取消</el-button>
      <el-button type="primary" @click="handleJoinMeetingConfirm">是，加入会议</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MeetingListPro from './MeetingListPro.vue'
import MeetingDialog from './MeetingDialog.vue'
import MeetingInvite from './MeetingInvite.vue'
import MeetingParticipants from './MeetingParticipants.vue'
import MeetingDetailDialog from './MeetingDetailDialog.vue'
// 会议 Webview 页面通过路由跳转：/meeting/webview
import { 
  getMeetingList, 
  postCreateMeeting, 
  postEditMeeting, 
  deleteMeeting, 
  postCancelMeeting,
  getMeetingDetail,
  postJoinMeeting
} from '@/axios/api/meeting'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUserInfo } from '@/utils/webStorage'
import { useGlobalStore } from '@/stores/globalStore'
import LfTabs from '@/components/commonUI/LfTabs.vue'
const globalStore = useGlobalStore()
//头部按钮点击
watch(
  () => globalStore.heaserClickInfo,
  (val) => {
    if (val === '会议') {
      openDialog()
    }
  },
)
const userInfo = getUserInfo()
const meetingClassList = ref([{
      id: "mine",
    name: "我创建的会议",
},{
      id: "joined",
    name: "我参与的会议",
},{
      id: "notStarted",
    name: "未开始的会议",
},{
      id: "ongoing",
    name: "进行中的会议",
},{
      id: "ended",
    name: "已结束的会议",
}])
const activeGroup = ref('mine')
const dialogVisible = ref(false)
const inviteVisible = ref(false)
const participantsVisible = ref(false)
const detailVisible = ref(false)
const editingMeeting = ref(null)
const inviteMeeting = ref(null)
const participantsMeeting = ref(null)
const detailMeeting = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const activeIndex = ref(0)
// 会议列表数据
const meetings = ref([])

// 查询类型映射
const queryTypeMap = {
  'mine': 1,      // 我创建
  'joined': 2,    // 我参与
  'notStarted': 3, // 未开始
  'ongoing': 4,   // 进行中
  'ended': 5      // 已结束
}

// 状态映射
const statusMap = {
  0: '未开始',
  1: '进行中',
  2: '已结束',
  3: '已取消'
}

// 检查join参数
const joinDialogVisible = ref(false)
const joinMeetingName = ref('')
const joinMeetingId = ref('')

const route = useRoute()
const router = useRouter()

const changeSubmitType = (index, id, name, scrollLeft) => {
  activeIndex.value = index
  activeGroup.value = id
  currentPage.value = 1
  fetchMeetingList()
}

// 获取会议列表
async function fetchMeetingList() {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      queryType: queryTypeMap[activeGroup.value]
    }
    
    const response = await getMeetingList(params)
    if (response?.code === 0) {
      meetings.value = response.result.records.map(meeting => ({
        ...meeting,
        status: statusMap[meeting.status] || '未知状态'
      }))
      total.value = response.result.total || response.result.records.length
    } else {
      // ElMessage.error(response?.msg || '获取会议列表失败')
    }
  } catch (error) {
    console.error('获取会议列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页变化
function handlePageChange(page) {
  currentPage.value = page
  fetchMeetingList()
}

// 处理每页数量变化
function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  fetchMeetingList()
}

function onGroupChange(index) {
  console.log(index)
  activeGroup.value = index
  currentPage.value = 1
  fetchMeetingList()
}
function openDialog(meeting = null) {
  if(userInfo.meeting !== 1) {
    ElMessage.error('您暂无创建会议权限，请联系管理员')
    return
  }

  editingMeeting.value = meeting
  dialogVisible.value = true
}
async function onSave(meeting) {
  try {
    const params = {
      title: meeting.title,
      startTime: meeting.startTime,
      durationMinutes: meeting.durationMinutes,
      detail: meeting.detail
    }
    
    let response
    if (meeting.id) {
      params.id = meeting.id
      response = await postEditMeeting(params)
    } else {
      response = await postCreateMeeting(params)
    }
    
    if (response.code === 0) {
      ElMessage.success(meeting.id ? '会议更新成功' : '会议创建成功')
      dialogVisible.value = false
      //fetchMeetingList() // 刷新列表
      changeSubmitType(0,"mine")
    } 
  } catch (error) {
    console.error('保存会议失败:', error)
  }
}

async function onDelete(meeting) {
  try {
    await ElMessageBox.confirm(
      `确定要删除会议"${meeting.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteMeeting({ meetingId: meeting.id })
    if (response.code === 0) {
      ElMessage.success('会议删除成功')
      fetchMeetingList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '会议删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会议失败:', error)
      ElMessage.error(error || '会议删除失败')

    }
  }
}

async function onCancel(meeting) {
  try {
    await ElMessageBox.confirm(
      `确定要取消会议"${meeting.title}"吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await postCancelMeeting({ meetingId: meeting.id })
    if (response.code === 0) {
      ElMessage.success('会议已取消')
      fetchMeetingList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '会议取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消会议失败:', error)
    }
  }
}

function onInvite(meeting) {
  inviteMeeting.value = meeting
  inviteVisible.value = true
}

function onExit(meeting) {
  // TODO: 调用退出会议接口
  ElMessage.success('已退出会议')
  fetchMeetingList() // 刷新列表
}

function onManageParticipants(meeting) {
  participantsMeeting.value = meeting
  participantsVisible.value = true
}

async function onViewDetail(meeting) {
  try {
    const response = await getMeetingDetail({ meetingId: meeting.id })
    if (response.code === 0) {
      detailMeeting.value = {
        ...meeting,
        ...response.result
      }
      console.log(detailMeeting.value);
      
      detailVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取会议详情失败')
    }
  } catch (error) {
    console.error('获取会议详情失败:', error)
  }
}

// 打开会议webview
function onJoinMeeting(meeting) {
  const roomId = meeting.roomId || meeting.id || 'test-room'
  router.push({
    path: '/meeting/webview',
    query: {
      id: meeting.id,
      title: meeting.title,
      roomId
    }
  })
  ElMessage.success(`正在进入会议室：${meeting.title}`)
}

// 加入会议
async function handleJoinMeetingConfirm() {
  try {
    const res = await postJoinMeeting(joinMeetingId.value)
    if (res.code === 0) {
      ElMessage.success('加入会议成功')
      joinDialogVisible.value = false
      fetchMeetingList()
      router.replace({ query: { ...route.query, join: undefined } })
      // 可选：跳转到会议详情或webview
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error(error)
  }
}

function handleJoinMeetingCancel() {
  joinDialogVisible.value = false
  // 可选：移除url参数
  router.replace({ query: { ...route.query, join: undefined } })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMeetingList()
  const joinParam = route.query.join
  if (joinParam) {
    joinMeetingId.value = joinParam
    // 获取会议详情
    getMeetingDetail({ meetingId: joinParam }).then(res => {
      if (res.code === 0 && res.result && res.result.title) {
        joinMeetingName.value = res.result.title
      } else {
        joinMeetingName.value = `ID: ${joinParam}`
      }
      joinDialogVisible.value = true
    }).catch(() => {
      joinMeetingName.value = `ID: ${joinParam}`
      // joinDialogVisible.value = true
    })
  }
})


</script>

<style scoped>
.meeting-page {
  /* background: #f6f8fa; */
  min-height: 100vh;
  padding-bottom: 24px;
  align-items: flex-start;
}
.meeting-sidebar {
  margin-top: 50px;
  /* margin-left: 30px; */
}
.flex-1.max-w-\[1200px\].min-w-0 {
  margin-top: 50px;
}
.sidebar-card {
  background: #fff;
  border-radius: 1.5rem;
  box-shadow: 0 4px 24px rgba(56,112,255,0.10);
  padding: 2.5rem 1.2rem 1.2rem 1.2rem;
  min-height: 420px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
}
.el-menu.rounded-2xl {
  border-radius: 1.2rem;
  box-shadow: none;
  background: transparent;
  border: none;
  margin-bottom: 2rem;
}
.sidebar-divider {
  height: 1px;
  background: #f0f3fa;
  margin: 0.5rem 0 1.2rem 0;
  border-radius: 1px;
}
.el-menu-item {
  border-radius: 0.8rem;
  margin-bottom: 0.5rem;
  font-size: 16px;
  font-weight: 600;
  color: #2563eb;
  transition: background 0.18s, color 0.18s;
}
.el-menu-item.is-active,
.el-menu-item:hover {
  background: linear-gradient(90deg, #e6f0fa 0%, #fafdff 100%);
  color: #1d4ed8;
}
.create-meeting-btn {
  background: linear-gradient(90deg, #2563eb 0%, #60a5fa 100%);
  color: #fff;
  font-weight: 700;
  font-size: 16px;
  padding: 0.9rem 0;
  box-shadow: 0 2px 12px 0 rgba(56,112,255,0.10);
  transition: box-shadow 0.18s, transform 0.18s, background 0.18s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
}
.create-meeting-btn:hover {
  background: linear-gradient(90deg, #1d4ed8 0%, #60a5fa 100%);
  box-shadow: 0 6px 24px 0 rgba(56,112,255,0.18);
  transform: translateY(-2px) scale(1.04);
}
.create-meeting-btn .el-icon {
  font-size: 18px;
  margin-right: 6px;
}
.bg-white {
  background: #fff;
}
.rounded-2xl {
  border-radius: 1.5rem;
}
.shadow-lg {
  box-shadow: 0 4px 24px rgba(56,112,255,0.10);
}
</style>
